﻿using Engine.UI;
using Message;
using UnityEngine;
using UnityEngine.UI;

namespace Login
{
    /// <summary>
    /// 注册面板
    /// </summary>
    public class RegisterView : ViewBase
    {
        private Button registerButton;
        private Button backButton;

        private InputField nameInputField;
        private InputField pwdInputField;
        private InputField rePwdInputField;

        public override string GetPath()
        {
            return "registerview";
        }

        public override void OnLoaded(Transform prefab)
        {
            base.OnLoaded(prefab);
            registerButton = prefab.Find("registerButton").GetComponent<Button>();
            backButton = prefab.Find("backButton").GetComponent<Button>();

            nameInputField = prefab.Find("nameInputField").GetComponent<InputField>();
            pwdInputField = prefab.Find("pwdInputField").GetComponent<InputField>();
            rePwdInputField = prefab.Find("rePwdInputField").GetComponent<InputField>();

            registerButton.onClick.AddListener(OnRegister);
            backButton.onClick.AddListener(OnBack);

            NetManager.Instance.OnConnect += OnConnect;
        }

        private void OnRegister()
        {
            //连接服务器
            if (NetManager.Instance.state != State.Connected)
            {
                NetManager.Instance.Connect();
                return;
            }
            else
            {
                Register();
            }
        }

        void OnConnect(State status)
        {
            Log.Debug("status:" + status.ToString());
            if (status == State.Connected)
            {
                Register();
            }
            if (status == State.TimeOut)
            {
                UIManager.Instance.Show<TipView>().SetTip("连接服务器超时!");
            }
            if (status == State.Error)
            {
                UIManager.Instance.Show<TipView>().SetTip("连接服务器出错!");
            }
        }

        void Register()
        {
            MsgManager.Instance.AddListener(typeof(S2CRegisterRet), OnRegisterRet);
            //提交 
            C2SRegister ctsr = new C2SRegister();
            ctsr.uname = nameInputField.text;
            ctsr.pwd = Helper.GetStringHash(pwdInputField.text);
            NetManager.Instance.Send(ctsr);
        }
        private void OnRegisterRet(object obj)
        {
            MsgManager.Instance.RemoveListener(typeof(S2CRegisterRet), OnRegisterRet);

            S2CRegisterRet stcr = obj as S2CRegisterRet;
            if (stcr.code == 0)
            {
                UIManager.Instance.Show<TipView>().SetTip("注册成功!");
            }
            else
            {
                UIManager.Instance.Show<TipView>().SetTip("注册失败!");
            }
        }

        private void OnBack()
        {
            Close();
            UIManager.Instance.Show<LoginView>();
        }
    }
}